﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;

namespace TireService.Web.UserControls
{
    public partial class ucEditCustomer : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void callbackEditCustomerPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerId)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            // Load form data
            LoadUserControlData(db);


            if (CustomerId != 0)
            {
                // Edit existing customer
                LoadCustomer(CustomerId, db);
            }
            else
            {
                // Create new Customer
                NewCustomer();
                // TODO: Write code
            }

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that load form data usercontrol
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void LoadUserControlData(TireServiceDB db)
        {
            // Prepare data for edit customer contact data
            ddlParentCompany.DataSource = db.GetParentCustomers();
            ddlParentCompany.ValueField = "CustomerId";
            ddlParentCompany.TextField = "CompanyName";
            ddlParentCompany.DataBind();

            ddlCountry.DataSource = db.GetCountries();
            ddlCountry.ValueField = "CountryId";
            ddlCountry.TextField = "CountryName";
            ddlCountry.DataBind();
        }

        /// <summary>
        /// Function that load tireset and set edit form values
        /// </summary>
        /// <param name="CustomerId">Id on customer to load</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomer(int CustomerId, TireServiceDB db)
        {
            // Bind item data to editform
            Customer customer = new Customer();
            customer = db.GetCustomer(CustomerId);

            if (customer != null)
            {
                // Set form fields
                // Customer info
                lblCustomerNumberValue.Text = customer.CustomerId.ToString();

                if (customer.ParentCustomerId != null)
                {
                    ddlParentCompany.Items.FindByValue(Convert.ToString(customer.ParentCustomerId)).Selected = true;
                    cbParentPayInvoice.ClientEnabled = true;
                    //pParentCompany.Visible = true;
                }
                else
                {
                    cbParentPayInvoice.ClientEnabled = false;
                    //pParentCompany.Visible = false;
                }
                //pIsCompany.Visible = customer.IsCompany;
                txtCompanyName.ClientEnabled = customer.IsCompany;
                txtCompanyNumber.ClientEnabled = customer.IsCompany;

                cbParentPayInvoice.Checked = customer.ParentPayInvoice;
                txtCompanyName.Text = customer.CompanyName;
                txtCompanyNumber.Text = customer.CompanyNumber;

                txtName.Text = customer.Name;
                txtAddress.Text = customer.Address;
                txtZipCode.Text = customer.ZipCode;
                txtCity.Text = customer.City;
                ddlCountry.Items.FindByValue(Convert.ToString(customer.CountryId)).Selected = true;
                txtSecondaryAddress.Text = customer.SecondaryAddress;
                txtSecondaryZipCode.Text = customer.SecondaryZipCode;
                txtSecondaryCity.Text = customer.SecondaryCity;
                txtPhone1.Text = customer.Phone1;
                ddlPhone1Type.Items.FindByValue(Convert.ToString(customer.Phone1Type)).Selected = true;
                if (customer.Phone2 != null) txtPhone2.Text = customer.Phone2;
                if (customer.Phone2 != null) ddlPhone2Type.Items.FindByValue(Convert.ToString(customer.Phone2Type)).Selected = true;
                txtEmail.Text = customer.Email;
                //rbPrimaryAddressTimeInterval.Value = (object)customer.OnPrimaryAddressInPrimeTime;
                rbPrimaryAddressTimeInterval.Items.FindByValue(customer.OnPrimaryAddressInPrimeTime.ToString().ToLower()).Selected = true;
                cbEconomicSync.Checked = customer.SyncToEconomic;
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde kunne ikke loades");
            }
        }

        private void NewCustomer()
        {
            // Clear form fields
            lblCustomerNumberValue.Text = "";
            ddlParentCompany.SelectedIndex = -1;
            //pParentCompany.Visible = false;
            cbParentPayInvoice.Checked = false;

            cbIsCompany.Checked = false;
            //pIsCompany.Visible = false;
            txtCompanyName.Text = "";
            txtCompanyNumber.Text = "";

            txtName.Text = "";
            txtAddress.Text = "";
            txtZipCode.Text = "";
            txtCity.Text = "";
            txtSecondaryAddress.Text = "";
            txtSecondaryZipCode.Text = "";
            txtSecondaryCity.Text = "";
            txtPhone1.Text = "";
            txtPhone2.Text = "";
            txtEmail.Text = "";
            rbPrimaryAddressTimeInterval.Value = "";

            // Show sync with economic checkbox
            cbEconomicSync.Enabled = true;
        }

        /// <summary>
        /// Callback function that saves customer
        /// </summary>
        protected void callBackSaveCustomer_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                // 0: CustomerId, 
                // 1: ParentCompany, 
                // 2: IsCompany, 
                // 3: ParentPayInvoice, 
                // 4: CompanyName, 
                // 5: CompanyNumber, 
                // 6: Name, 
                // 7: Address, 
                // 8: ZipCode, 
                // 9: City, 
                // 10: Country, 11: SecAddress, 12: SecZipCode, 13: SecCity, 14: Phone1, 15: Phone2, 16: Phone1Type, 17: Phone2Type, 18: Email, 19: AddressTimeInterval, 
                // 20: SyncToEconomic
                string[] param = e.Parameter.Split('|');

                // TODO: Review below - change so input comes from client

                int CustomerId = Convert.ToInt32(param[0]);

                TireServiceDB db = new TireServiceDB();

                // Create customer
                Customer customer = new Customer();

                bool parentcompany = false;
                int? parentcustomerid = null;
                bool parentpayinvoice = false;
                string companyname = null;
                string companynumber = null;
                int? phone2type = null;
                string phone2 = null;

                // Check if childcompany (has parentcompany value)
                if (param[1] != "null")
                {
                    parentcompany = true;
                    parentcustomerid = Convert.ToInt32(param[1]);
                    parentpayinvoice = Convert.ToBoolean(param[3]);
                }

                // Check if company
                if (Boolean.Parse(param[2]))
                {
                    companyname = param[4];
                    companynumber = param[5];
                }

                // Check if second phone added
                if (param[17] != "null")
                {
                    phone2type = Convert.ToInt32(param[17]);
                    phone2 = param[15];
                }
                
                CustomerBLL customerBLL = new CustomerBLL();
                customer = customerBLL.UpdateCustomer(
                                            db,
                                            customer,
                                            CustomerId,
                                            parentcompany,
                                            parentcustomerid,
                                            parentpayinvoice,
                                            Boolean.Parse(param[2]),
                                            companyname,
                                            companynumber,
                                            param[6],
                                            param[7],
                                            param[8],
                                            param[9],
                                            Convert.ToInt32(param[10]),
                                            param[11],
                                            param[12],
                                            param[13],
                                            param[14],
                                            Convert.ToInt32(param[16]),
                                            phone2,
                                            phone2type,
                                            param[18],
                                            Boolean.Parse(param[19]),
                                            Boolean.Parse(param[20]),
                                            false, // Manual Invocing - TODO: Improve
                                            false, // PBS Invocing - TODO: Improve
                                            false
                                        );

                // Send back customerid to client
                e.Result = customer.CustomerId.ToString();

                // Dispose connection to database
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }
    }
}